const fs = require('fs')
const formidable = require('formidable')
const path = require('path')
const translate = require('../translates/baidu')


function waitTime(time = 1500){
    return new Promise((res) => {
        setTimeout(() => {
            res()
        }, time);
    })
}


let a = 1
let b = 0
async function deepTranslate2(node){
    let res = node.constructor === Array ? [] : {};
    for(let k in node){
        if(node[k] instanceof Array){
            res[k] = []
            res[k][a] = node[k][a]
            if(node[k][b]){
                res[k][b] = node[k][b]
            }else{
                await waitTime(700)
                try {
                    let r = await translate(node[k][a])
                    console.log(node[k][a], r.res)
                    res[k][b] = r.res
                }catch(err){
                    res[k][b] = ''
                    console.log(err, `翻译${node[k][a]}失败！！！`)
                }
            }
        }else if(Object.prototype.toString.call(node) === '[object Object]'){
            res[k] = await deepTranslate2(node[k])
        }else{
            console.log('出现不是数组也不是对象类型！！！')
        }
    }
    return res
};

module.exports = (req, res) => {
    let form = new formidable.IncomingForm();
    form.parse(req, async function (err, fields, files) {
        let oPath = files.file.filepath;

        const file = require(oPath)

        let r  = await deepTranslate2(file)
        let p = path.resolve(__dirname, "../../tmp") + `/res${Date.now()}.json`

        fs.writeFileSync(p, JSON.stringify(r))

        res.sendFile(path.resolve(p))
    })
}